<!--
 * @Description: 组织管理
 * @Author: wangwangwang
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-29 09:52:39
-->
<template>
  <div class="pages_content table organization">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex">
        <div class="main_left scroll" style="width: 230px; padding: 20px">
          <div style="padding-right:10px;">
            <el-tree :data="treearr" :props="defaultProps" class="tree-line"  :indent="0"  node-key="id" :default-expanded-keys="[
            'parent_id']" :expand-on-click-node="false" @node-click="setTree">
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <div v-if="data.imgIcon" style="display: inline-block;width:17px;height:26px;padding:8px 3px 0 0">
                  <img style="width:14px;height:14px" :src="data.imgIcon" />
                </div>
                <span style="padding-right:10px;">{{ node.label }}</span>
              </span>
            </el-tree>
          </div>

        </div>
        <div class="main_right">
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
              </span>
              <span v-show="showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <el-form ref="form" size="medium" :inline="true" :model="form">
                  <el-form-item label="组织名称" prop="shortName" label-width="110px">
                    <el-input v-model="form.name" placeholder="请输入"></el-input>
                  </el-form-item>
                  <el-form-item label="编码" prop="code">
                    <el-input v-model="form.code" placeholder="请输入"></el-input>
                  </el-form-item>
                  <!-- <el-form-item label="简称" prop="shortName" label-width="110px">
                    <el-input v-model="form.shortName"></el-input>
                  </el-form-item> -->

                  <el-form-item>
                    <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="initData()">查询</el-button>
                    <el-button size="medium" class="bottom_all_two" @click="resetData()">重置</el-button>
                  </el-form-item>
                  <div style="margin-bottom: 15px">
                    <el-checkbox v-model="showChild">显示所有下级组织</el-checkbox>
                    <el-checkbox v-model="showVisual">显示虚拟组织</el-checkbox>
                    <el-checkbox v-model="showEnable">显示已禁用的组织</el-checkbox>
                  </div>
                </el-form>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" style="margin-left: 0" size="small" class="bottom_all" @click="add()">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
                  添加
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="updateType(1)">
                  <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px"></i>
                  启用
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="updateType(2)">
                  <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px"></i>
                  禁用
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="updateType(3)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                  删除
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='GUANLIZPZ'))!==-1" size="small" class="botton_five" @click="show()">管理者配置</el-button>
              </div>
              <div>
                <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUNPXH'))!==-1" :underline="false" @click="updateSortNum()">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_sort1"></i>
                  </span>
                  保存排序号
                </el-link>
                <el-dropdown trigger="click" style="margin: 0 20px">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index1) in table" :key="index1">
                      <el-checkbox v-model="item.status">{{
                        item.label
                        }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAOCHU'))!==-1" :underline="false" @click="$Download(DownloadURL, form);">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_export1"></i>
                  </span>
                  导出
                </el-link>
              </div>
            </div>
            <div class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection"></el-table-column>
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :min-width="item.width" :fixed=" item.label =='操作'?'right':false">
                    <template slot-scope="scope">
                      <div v-if="item.label == '状态'">
                        <span v-if="scope.row.enable == 0 " style="color: #969799">禁用</span>
                        <span v-if="scope.row.enable == 1" style="color: #00a754">启用</span>
                      </div>
                      <div v-else-if="item.label == '操作'">
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="update(scope.row)">

                          修改
                        </el-button>
                      </div>
                      <div v-else-if="item.label == '是否虚拟组织'">
                        <span v-if="scope.row.virtualOrganization == 0" style="color: #00a754">否</span>
                        <span v-if="scope.row.virtualOrganization == 1 " style="color: #969799">是</span>
                      </div>
                      <div v-else-if="item.label == '组织名称'">
                        {{scope.row.field2||scope.row.name}}
                      </div>

                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
            <div v-if="treeshou" class="card_bottom">
              <div class="card_bottom_left">
                <div class="top_page_totle">总共{{ total }}条</div>
                <el-pagination :current-page.sync="page" :page-size="10" layout="prev, pager, next, jumper" :total="total" @current-change="initData()"></el-pagination>
              </div>
              <div>
                <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="initData()">刷新</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false" :before-close="resefrom">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <div class="nav-one" style="min-height: 530px;">
        <div class="navone-nav">
          <div :class="checkindex ==0 ? 'active' : ''" @click="checkindex = 0"><span class="navone-nav-span" :class="checkindex==0?'navone-nav-span0':''">基本信息</span></div>
          <div :class="checkindex ==1 ? 'active' : ''" @click="checkindex = 1"><span class="navone-nav-span" :class="checkindex==1?'navone-nav-span0':''">属性</span></div>
        </div>
        <div class=" navone-info">
          <el-form v-show="checkindex ==0" ref="dialogForm" style="padding: 0px 20px 0px 0px;" :rules="rules" :model="dialogForm" label-width="68px">
            <el-form-item prop="code">
              <span slot="label" style="width: 90px; color: #ff0000">编码</span>
              <el-input v-model="dialogForm.code" placeholder="请输入" @input="changecode"></el-input>
            </el-form-item>
            <el-form-item prop="name">
              <span slot="label" style="width: 90px; color: #ff0000">名称</span>
              <el-input v-model="dialogForm.name" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="简称">
              <el-input v-model="dialogForm.shortName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="typeId">
              <el-select v-model="dialogForm.typeId" placeholder="请选择" style="width: 100%">
                <el-option v-for="(item, index3) in typeoptions" :key="index3" :label="item.itemName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="图标" prop="imgIcon">
              <el-upload class="avatar-uploader" action="/resource/resources/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="upheader">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="是否虚拟组织">
              <el-select v-model="dialogForm.virtualOrganization" placeholder="请选择" style="width: 100%">
                <el-option value="0" label="否"></el-option>
                <el-option value="1" label="是"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序号">
              <el-input v-model="dialogForm.sortNum" type="Number" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="enable">
              <el-radio-group v-model="dialogForm.enable">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-table v-show="checkindex ==1" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="dialogForm.attributes" tooltip-effect="dark">
            <el-table-column align="center" label="属性名" prop="attributeName"></el-table-column>
            <el-table-column align="center" label="属性值">
              <template slot-scope="scope">
                <el-select ref="selection1" v-model="scope.row.attributeValueId" placeholder="请选择" style="width: 100%">
                  <el-option v-for="(item4, index4) in alloptions[scope.row.field1].items" :key="index4" :label="item4.itemName" :value="item4.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resefrom">取 消</el-button>
        <el-button class="bottom_all" @click="sureSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 管理者配置 -->
    <el-dialog v-dialogDrag :visible.sync="managerconfig" width="1072px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">管理者配置</span>
      <div class="managerconfig" style="padding: 0; width: 100%">
        <div class="dialoginfo-info">
          <div class="dialoginfo-info-div">
            <div class="dialoginfo-info-title">组织</div>
            <div class="dialoginfo-info-info">
              <el-tree :data="orarr" :props="defaultProps" class="tree-line"  :indent="0"  :expand-on-click-node="false" @current-change="HandleChangeOrg">
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <i :class="data.icon" :style="'color:' + data.color"></i>
                  <span>{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
          </div>
          <div class="dialoginfo-info-center"></div>
          <div class="dialoginfo-info-div">
            <div class="dialoginfo-info-title second-title">
              <div :class="
                  curTabIndex == 0
                    ? 'second-title-bg-none'
                    : 'second-title-bg-active'
                " @click="handleSwitchTab(0)">
                <div class="second-title-text">分管领导</div>
              </div>
              <div :class="
                  curTabIndex == 1
                    ? 'second-title-bg-none'
                    : 'second-title-bg-active'
                " @click="handleSwitchTab(1)">
                <div class="second-title-text">主管</div>
              </div>
              <div :class="
                  curTabIndex == 2
                    ? 'second-title-bg-none'
                    : 'second-title-bg-active'
                " @click="handleSwitchTab(2)">
                <div class="second-title-text">副主管</div>
              </div>
            </div>
            <div v-show="this.curOrgId" class="dialoginfo-info-info">
              <div>
                <el-input v-model="keyword" size="mini" placeholder="请输入内容" suffix-icon="el-icon-search" clearable @input="getUserList"></el-input>
              </div>
              <el-radio-group v-if="curTabIndex == 0 || curTabIndex == 1" v-model="curUserId" style="padding: 10px">
                <div v-for="(item, index) in filteruserarr" :key="index" class="user">
                  <el-radio :label="item.id">
                    {{ item.name || item.updateUserName }}
                  </el-radio>
                </div>
              </el-radio-group>
              <el-checkbox-group v-if="curTabIndex == 2" v-model="curUserIds" style="padding: 10px">
                <div v-for="(item, index) in filteruserarr" :key="index" class="user">
                  <el-checkbox :label="item.id" :value="item.id">
                    {{ item.name || item.updateUserName }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="managerconfig = false">关 闭</el-button>
        <el-button class="bottom_all" @click="Submit()">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import styles from "@/app.scss";
import {
  queryPage,
  saveOrUpdate,
  updateOrDelete,
  usersaveOrUpdate,
  usergetList,
  Download,
  getsList,
  get_attribute_list,
  update_sort_num
} from '@/api/basedata/organization.js'
import { queryPage as queryuserPage } from '@/api/basedata/user'
import { getDicsType } from '@/api/common.js'
import breaDcrumb from '@/components/breadcrumb'
import { mapGetters } from 'vuex'
import { transData } from '@/utils/utils'
import { codeReg } from '@/common/RegExp.js'
import { getToken, getUserId } from '@/utils/auth';
export default {
  name: 'organization',
  components: {
    breaDcrumb
  },
  data() {
    return {
      upheader: {
        "access-token": getToken(),
        "user-id": getUserId(),
      },
      treeshou: true,
      alloptions: {},
      checkindex: 0,
      DownloadURL: Download,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        typeId: [{ required: true, message: '请选择类型', trigger: 'change' }],
      },
      /* 管理者配置*/
      userId: '',
      orarr: [],
      userarr: [],
      filteruserarr: [],
      curOrgId: '',
      totalarr: [],
      /* 一*/
      curUserId: '',
      curUserIds: [],
      preSelectedUser: {
        'arr0': [],
        'arr1': [],
        'arr2': []
      },
      leaderIda: '',
      directorIda: '',
      secdirectorIds: [],
      orangeotreekId: '',
      Ids: [],
      keyword: '',
      /* 管理者配置*/
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      managerconfig: false,
      curTabIndex: 0, // 组织管理的分页序号
      /* 添加修改弹窗*/
      dialogVisible: false,
      dialogtitle: '',
      /* 弹要修改过着添加的数据*/
      /* 判断收起展开*/
      showCardNav: true,
      /* 类型*/
      typeoptions: [],
      /* 列表选中的数据集*/
      SelectionTableData: [],
      tableData: [],
      page: 1,
      parentId: 'parent_id',
      dialogForm: {
        code: '',
        name: '',
        shortName: '',
        imgIcon: '',
        // classifyId: "",
        classifyName: '',
        classifyValue: '',
        typeId: null,
        typeName: '',
        typeValue: '',
        parentId: '',
        sortNum: null,
        virtualOrganization: '0',
        enable: 1,
        attributes: [
          { attributeName: '工资计算规则', attributeNameId: 'aec527603fc14c43b9b94729746844a9', attributeValueId: '', field1: 'WageCalculationRules' },
          { attributeName: '机构区域类型', attributeNameId: '99e04b8fe7364660aa2eca0a6f1bf6a5', attributeValueId: '', field1: 'MechanismAreaType' },
          { attributeName: '行业', attributeNameId: 'b1d057906f064a979a203a6c2ffe51e7', attributeValueId: '', field1: 'industry' },
          { attributeName: '每天午餐补贴', attributeNameId: '12fe8a04f3074f12814f523c0c083a96', attributeValueId: '', field1: 'DailyLunchAllowance' },
          { attributeName: '机构级别', attributeNameId: '73b321948e9f4562a2d79a604f288d49', attributeValueId: '', field1: 'InstitutionalLevel' },
          { attributeName: '是否工资主体', attributeNameId: '1054605c19124663af6ab6bf51b5e533', attributeValueId: '', field1: 'WhetherItIsAWageSubject' }
        ]
      },
      form: {
        code: '',
        // shortName: "",
        name: ''
      },
      total: 0,
      showChild: true,
      showEnable: false,
      showVisual: false,
      table: [
        { label: '编码', width: '160', prop: 'code', status: true },
        { label: '组织名称', width: '220', prop: 'name', status: true },
        { label: '简称', width: '160', prop: 'shortName', status: true },
        { label: '类型', width: '100', prop: 'typeName', status: true },
        {
          label: '分管领导',
          width: '100',
          prop: 'branchLeaderName',
          status: true
        },
        { label: '主管', width: '100', prop: 'chargeName', status: true },
        {
          label: '副主管',
          width: '100',
          prop: 'deputyChargeName',
          status: true
        },
        {
          label: '是否虚拟组织',
          width: '120',
          prop: 'virtualOrganization',
          status: true
        },
        { label: '排序号', width: '120', prop: 'sortNum', status: true },
        { label: '状态', width: 'auto', prop: 'entrance', status: true },
        { label: '操作', width: '120', prop: '', status: true }
      ],
      treearr: [],
      tmpSubmitData: {},
      Sorts: [],
      ButtonList: [],
      loading: false,
      curUserIdCP: '',
      curUserIdsCP: [],
      oldtypeoptions: [],
      submitData: [],//提交的数据
      imageUrl: '',
    }
  },
  computed: {
    ...mapGetters({
      screenWidth: 'getscreenWidth',
      screenHeight: 'getscreenHeight',
      Collapse: 'getsCollapse'
    }),
    style() {
      let num = 0
      if (this.Collapse) {
        num = this.screenWidth - 325
      } else {
        num = this.screenWidth - 421
      }
      return 'width:' + num + 'px;'
    }
  },
  beforeCreate() {
    getDicsType({ codes: 'orangeType,WageCalculationRules,MechanismAreaType,industry,DailyLunchAllowance,InstitutionalLevel,WhetherItIsAWageSubject' }).then(res => {
      this.oldtypeoptions = JSON.parse(JSON.stringify(res.data.orangeType.items))
      this.alloptions = res.data
    })
  },
  created() {
    this.initPositionList()
    this.ButtonList = this.$ButtonList()
  },
  mounted() {
    this.initData()
  },
  methods: {
    /** 保存排序号*/
    updateSortNum() {
      update_sort_num(this.Sorts).then(res => {
        if (res.code == 1001) {
          this.$message({
            message: '更新成功',
            type: 'success'
          })
        }
      })
    },
    /** 文件上传*/
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      if (res.code === 1001) {
        this.dialogForm.imgIcon = res.data.fileUrl;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    changecode() {
      this.dialogForm.code = codeReg(this.dialogForm.code)
    },
    /**判断数据删除和新增；是否有改 */
    submitDataFun() {
      console.log('数据');
      this.submitData = [];
      if (this.curTabIndex === 0 || this.curTabIndex === 1) {
        console.log(this.curUserIdCP);
        console.log(this.curUserIdCP.userId);
        if (this.curUserIdCP.userId) {
          if (this.curUserId != this.curUserIdCP.userId) {
            this.loading = true
            console.log(0);
            this.submitData.push({
              organizationId: this.curOrgId,
              status: 0,
              userId: this.curUserIdCP.userId,
              userType: this.curTabIndex + 1,
            })
          }
        }
        if (this.curUserId) {
          if (!this.curUserIdCP.userId) {
            console.log(1.5);
            this.loading = true
          }
          let item = this.filteruserarr.find((res) => res.id == this.curUserId)
          console.log(1);
          this.submitData.push({
            organizationId: this.curOrgId,
            status: 1,
            userId: item.id,
            userType: this.curTabIndex + 1,
          })
        }
      } else if (this.curTabIndex === 2) {
        let arry = []
        this.curUserIds.forEach((v) => {
          this.filteruserarr.forEach((v2) => {
            if (v == v2.id) {
              arry.push(v2)
            }
          })
        })
        let update = arry.filter((res) =>
          this.curUserIdsCP.some((item) => res.id == item.userId)
        );
        let deleteData = this.curUserIdsCP.filter(
          (res) => !update.some((item) => res.userId == item.id)
        );
        deleteData.forEach((res) => {
          res.status = 0; //0是删除
        });
        let addData = arry.filter(
          //新增的type默认写死为 1
          (res) => !update.some((item) => res.id == item.id)
        );
        if (addData.length > 0 || deleteData.length > 0) {
          this.loading = true
        }
        console.log(JSON.parse(JSON.stringify(addData)))
        console.log(JSON.parse(JSON.stringify(deleteData)))
        deleteData.forEach((v) => {
          this.submitData.push({
            organizationId: this.curOrgId,
            status: 0,
            userId: v.userId,
            userType: this.curTabIndex + 1,
          })
        })
        addData.forEach((v) => {
          this.submitData.push({
            organizationId: this.curOrgId,
            status: 1,
            userId: v.id,
            userType: this.curTabIndex + 1,
          })
        })
      }
      console.log(JSON.parse(JSON.stringify(this.submitData)))
    },
    /** 保存组织*/
    async Submit() {
      this.submitDataFun()
      if (this.submitData.length > 0) {
        await usersaveOrUpdate(this.submitData).then(() => {
          this.HandleChangeOrg()
        })
      } else {
        this.$message({
          message: '请选择用户',
          type: 'warning'
        });
      }
    },

    /**
     * 管理者配置的实现思路：
     * 将修改数据放入数据，然后提交。其中包括：
     * 1. 切换，原数据如果是系统数据，则status改为0，否则直接删除
     * 2. 对于原系统没有修改的部分，不做处理。因此，需要特定字段表示是元系统数据。
     * 数据结构：
     *   {
     *     组织编号: [{item}， {item}]
     *   }
     * @param {[type]} e [description]
     */
    /**组织切换 */
    async HandleChangeOrg(e) {
      if (e) {
        await this.submitDataFun()
        if (this.loading) {
          await this.$confirm("请先保存数据，取消后数据将会丢失?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            cancelButtonClass: "bottom_all_two",
            confirmButtonClass: "bottom_all",
            type: "warning",
          }).then(async () => {
            await this.Submit();
            this.HandleChangeOrgOk(e)
          }).catch(() => {
            this.HandleChangeOrgOk(e)
          });
        } else {
          this.HandleChangeOrgOk(e)
        }
      } else {
        this.HandleChangeOrgOk()
      }
    },
    /**查询选中项 */
    HandleChangeOrgOk(e) {
      this.loading = false
      this.curUserId = ''
      this.curUserIds = []
      this.curUserIdCP = ''
      this.curUserIdsCP = []
      if (e) {
        console.log(JSON.parse(JSON.stringify(e)))
        this.curOrgId = e.id
      }
      if (this.curOrgId) {
        if (this.curTabIndex === 0) {
          usergetList({ organizationId: this.curOrgId, userType: 1 }).then((res) => {
            if (res.data.length) {
              this.curUserId = res.data[0].userId
              this.curUserIdCP = JSON.parse(JSON.stringify(res.data[0]))
            }
          })
        } else if (this.curTabIndex === 1) {
          usergetList({ organizationId: this.curOrgId, userType: 2 }).then((res) => {
            if (res.data.length) {
              this.curUserId = res.data[0].userId
              this.curUserIdCP = JSON.parse(JSON.stringify(res.data[0]))
            }
          })
        } else if (this.curTabIndex === 2) {
          usergetList({ organizationId: this.curOrgId, userType: 3 }).then((res) => {
            this.curUserIds = []
            this.curUserIdsCP = res.data
            res.data.forEach((item) => {
              this.curUserIds.push(item.userId)
            })
          })
        }
      }
    },

    /**
     * 选择操作
     * @param {boolean} val
     * @param {[type]} event [description]
     */
    rmOrgItemByType(userType) {
      const item = this.tmpSubmitData[this.curOrgId]

      if (item) {
        this.tmpSubmitData[this.curOrgId] = item.filter(item => {
          let ret = true
          if (item.userType === userType) {
            if (item.isOldData) {
              item.status = 0
            } else {
              ret = false
            }
          }

          return ret
        })
      }
    },

    rmOrgItemById(userId) {
      const item = this.tmpSubmitData[this.curOrgId]

      if (item) {
        this.tmpSubmitData[this.curOrgId] = item.filter(item => {
          let ret = true
          if (item.userId === userId) {
            if (item.isOldData) {
              item.status = 0
            } else {
              ret = false
            }
          }

          return ret
        })
      }
    },
    /**
     * 初始化选择对象：将已经选择的数据，在界面显示
     * @param  {[type]} arr  [description]
     * @param  {[type]} data [description]
     * @param  {[type]} key  [description]
     * @return {[type]}      [description]
     */
    setorarr(arr, data, key) {
      for (const a in arr) {
        if (arr[a].id == this.curOrgId) {
          arr[a][key] = data
          break
        } else {
          if (arr[a].children) {
            this.setorarr(arr[a].children, data, key)
          }
        }
      }
    },
    getorarr(arr) {
      arr.forEach((res) => {
        // if (res.leaderIda !== "") {
        //   this.totalarr.push(new Binding(1, res.leaderIda, res.id));
        // }
        // if (res.directorIda !== "") {
        //   this.totalarr.push(new Binding(2, res.directorIda, res.id));
        // }
        // if (res.secdirectorIds.length !== 0) {
        //   res.secdirectorIds.forEach((item) => {
        //     this.totalarr.push(new Binding(3, item, res.id));
        //   });
        // }
        if (res.children) {
          this.getorarr(res.children)
        }
      })
    },
    show() {
      this.getUserList()
      this.managerconfig = true
      this.curTabIndex = 0
      /* 获取组织树*/
      this.orarr = []
      this.filteruserarr = []
      this.preSelectedUser = {
        'arr0': [],
        'arr1': [],
        'arr2': []
      }
      this.tmpSubmitData = {}

      const params = {
        page: 1,
        pageSize: 10000000
      }
      queryPage(params).then((res) => {
        if (res.code === 1001) {
          res.data.data.forEach((item) => {
            item.leaderIda = ''
            item.directorIda = ''
            item.secdirectorIds = []
          })
          const { data } = res.data;
          this.orarr = transData(
            data,
            'id',
            'parentId',
            'children',
            'parent_id'
          )
        }
      })
    },

    /**
     * 获取用户列表，处理回显
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */
    getUserList(name) {
      const params = {
        page: 1,
        pageSize: 100000,
        name: name
      }
      // const type = this.curTabIndex + 1
      // const item = this.tmpSubmitData[this.curOrgId]
      // if (item && item.length) {
      //   if ([0, 1].indexOf(this.curTabIndex)) {
      //     this.curUserId = ''
      //     item.forEach(item => {
      //       if (item.status === 1 && item.userType == type) {
      //         this.curUserId = item.userId
      //       }
      //     })
      //   } else {
      //     const ids = []

      //     item.forEach(item => {
      //       if (item.status === 1 && item.userType == type) {
      //         ids.push(item.userId)
      //       }
      //     })

      //     this.curUserIds = ids
      //   }
      // } else {
      //   this.curUserId = ''
      //   this.curUserIds = []
      // }
      queryuserPage({ ...params, userEentrance: 'entrance_manager' }).then(
        (res) => {
          const ids = []
          this.preSelectedUser['arr' + this.curTabIndex].forEach(item => {
            ids.push(item.id)
          })

          let users = res.data.data
          if (ids.length) {
            users = users.filter(item => {
              return ids.indexOf(item.id) === -1
            })
          }
          this.filteruserarr = this.preSelectedUser['arr' + this.curTabIndex].concat(users)
          console.log(JSON.parse(JSON.stringify(this.filteruserarr)))
        }
      )
    },
    handleSwitchTab(num) {
      this.submitDataFun()
      if (this.loading) {
        this.$confirm("请先保存数据，取消后数据将会丢失?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        }).then(() => {
          this.Submit();
          this.curTabIndex = num
          this.HandleChangeOrg()
        }).catch(() => {
          this.submitData = [];
          this.curTabIndex = num
          this.keyword = ''
          this.HandleChangeOrg()
        });
      } else {
        this.curTabIndex = num
        this.keyword = ''
        this.HandleChangeOrg()
      }
    },
    /* 接受树状数据*/
    setTree(e) {
      getsList({ parentId: e.id }).then(res => {
        this.tableData = res.data
        this.treeshou = false
      })
      if (this.parentId == e.id) {
        return
      }
      this.parentId = e.id
    },
    initPositionList() {
      const params = {
        page: 1,
        pageSize: 10000
      }
      queryPage(params).then((res) => {
        if (res.code === 1001) {
          const { data } = res.data;
          let Arry = transData(
            data,
            'id',
            'parentId',
            'children',
            'parent_id'
          )
          this.treearr = [{
            children: Arry,
            name: '组织树',
            id: 'parent_id'
          }]
        }
      })
    },
    initData() {
      const params = {
        ...this.form,
        page: this.page,
        pageSize: 10,
        showChild: this.showChild ? 1 : 0,
        showEnable: this.showEnable ? 1 : 0,
        showVisual: this.showVisual ? 1 : 0
      }
      queryPage(params).then((res) => {
        if (res.code === 1001) {
          this.tableData = res.data.data
          this.total = res.data.totalRows
        }
      })
    },
    resetData() {
      this.form.name = ''
      this.form.code = ''
      this.parentId = 'parent_id'
      this.showChild = true
      this.showEnable = false
      this.showVisual = false
      this.treeshou = true
      this.initData()
    },
    resefrom() {
      this.dialogVisible = false
    },
    add() {
      if (this.parentId == 'parent_id') {
        this.typeoptions = this.oldtypeoptions.filter(res => (res.id == '19da56b9e85648059e3cf1e7da497da4' || res.id == '94446b7fe67548eca859ee7f1f8e8f7b' || res.id == 'b8f9367217ab43f8924cd6c08a9ba300'))
      } else {
        this.typeoptions = this.oldtypeoptions
      }

      this.dialogVisible = true;
      this.imageUrl = ''
      this.checkindex = 0
      this.$data.dialogForm = this.$options.data().dialogForm
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate()
      }, 10)
      this.dialogtitle = '添加组织'
    },
    updateType(index) {
      const self = this
      self.checkindex = 0
      if (self.SelectionTableData.length == 0) {
        this.$message({
          message: '警告哦，请勾选要进行操作的数据',
          type: 'warning'
        })
        return
      }
      this.$confirm(
        `确定${index === 1 ? '启用' : index === 2 ? '禁用' : '删除'
        }选中的数据?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'bottom_all_two',
          confirmButtonClass: 'bottom_all',
          type: 'warning'
        }
      )
        .then(() => {
          switch (index) {
            case 1: {
              const params = {
                status: 1,
                type: 'update_enable'
              }
              self.handleData(params)
              return
            }
            case 2: {
              const params = {
                status: 0,
                type: 'update_enable'
              }
              self.handleData(params)
              return
            }
            case 3: {
              const params = {
                status: 0,
                type: 'update_status'
              }
              self.handleData(params)
              return
            }
            default:
              break
          }
        })
        .catch(() => { })
    },
    handleData(data) {
      const params = {
        ...data,
        ids: this.SelectionTableData
      }
      updateOrDelete(params).then((res) => {
        if (res.code === 1001) {
          this.initData()
          this.treearr = []
          this.initPositionList()
          this.$message({
            message: '操作成功！',
            type: 'success'
          })
        }
      })
    },
    update(data) {
      this.checkindex = 0
      const formData = {
        id: data.id,
        code: data.code,
        name: data.name,
        shortName: data.shortName,
        imgIcon: data.imgIcon,
        // classifyId: data.classifyId,
        classifyName: data.classifyName,
        classifyValue: data.classifyValue,
        typeId: data.typeId,
        typeName: data.typeName,
        typeValue: data.typeValue,
        parentId: data.parentId,
        sortNum: data.sortNum,
        virtualOrganization: JSON.stringify(data.virtualOrganization),
        enable: data.enable,
        attributes: data.attributes
      }
      get_attribute_list({ organizationId: data.id }).then(res => {
        formData.attributes = res.data
        if (res.data.length == 0) {
          formData.attributes = [
            { attributeName: '工资计算规则', attributeNameId: 'aec527603fc14c43b9b94729746844a9', attributeValueId: '', field1: 'WageCalculationRules' },
            { attributeName: '机构区域类型', attributeNameId: '99e04b8fe7364660aa2eca0a6f1bf6a5', attributeValueId: '', field1: 'MechanismAreaType' },
            { attributeName: '行业', attributeNameId: 'b1d057906f064a979a203a6c2ffe51e7', attributeValueId: '', field1: 'industry' },
            { attributeName: '每天午餐补贴', attributeNameId: '12fe8a04f3074f12814f523c0c083a96', attributeValueId: '', field1: 'DailyLunchAllowance' },
            { attributeName: '机构级别', attributeNameId: '73b321948e9f4562a2d79a604f288d49', attributeValueId: '', field1: 'InstitutionalLevel' },
            { attributeName: '是否工资主体', attributeNameId: '1054605c19124663af6ab6bf51b5e533', attributeValueId: '', field1: 'WhetherItIsAWageSubject' }
          ]
        }
      })
      if (formData.parentId == 'parent_id') {
        this.typeoptions = this.oldtypeoptions.filter(res => (res.id == '19da56b9e85648059e3cf1e7da497da4' || res.id == '94446b7fe67548eca859ee7f1f8e8f7b' || res.id == 'b8f9367217ab43f8924cd6c08a9ba300'))
      } else {
        this.typeoptions = this.oldtypeoptions
      }
      this.imageUrl = data.imgIcon ? process.env.VUE_APP_API_FILe + data.imgIcon : '';
      this.dialogForm = formData
      this.dialogForm.status = 1
      this.dialogtitle = '修改组织'
      this.dialogVisible = true
    },
    handleSelectionChange(val) {
      const data = []
      const data1 = []
      for (const i of val) {
        data.push(i.id)
        data1.push({ id: i.id, sortNum: i.sortNum })
      }
      this.SelectionTableData = data
      this.Sorts = data1
    },
    sureSubmit() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          if (!this.dialogForm.id) {
            this.dialogForm.parentId = this.parentId
          }
          this.typeoptions.forEach((item) => {
            if (this.dialogForm.typeId == item.id) {
              this.dialogForm.typeName = item.itemName
              this.dialogForm.typeValue = item.itemValue
            }
          })
          if (this.dialogForm.id) {
            this.dialogForm.attributes.forEach(res => {
              res.organizationId = this.dialogForm.id
            })
          }
          const params = {
            ...this.dialogForm
          }
          saveOrUpdate(params).then((res) => {
            if (res.code === 1001) {
              this.$message({
                message: '操作成功！',
                type: 'success'
              })
              this.initData()
              this.treearr = []
              this.initPositionList()
              this.resefrom()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },

}
</script>
<style lang="scss">
.organization {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: $bg_color;
  }
  .avatar-uploader-icon {
    font-size: 16px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
}
</style>

<style lang="scss" scoped>
.el-tree {
  display: inline-block;
}
.iconfont {
  font-size: 14px;
  padding-right: 5px;
}
.second-title-text {
  font-size: calc(#{$font_size} + 2px);
  font-weight: 400;
}
.second-title {
  padding-left: 0 !important;
  display: flex;
  .second-title-bg-none {
    background-color: #fff;
    width: calc(100% / 3);
    display: flex;
    justify-content: center;
    > div {
      height: 47px;
      color: $bg_color;
      border-bottom: 2px $bg_color solid;
    }
  }
  .second-title-bg-active {
    width: calc(100% / 3);
    display: flex;
    justify-content: center;
    > div {
      height: 47px;
    }
  }
}
.managerconfig {
  .dialoginfo-info {
    padding: 20px;
    display: flex;
    padding-top: 24px;
    .dialoginfo-info-div {
      width: 496px;
      height: 517px;
      border: 1px solid #e1e5ed;
      overflow: hidden;
    }
    .dialoginfo-info-title {
      padding-left: 20px;
      height: 48px;
      background: #e1e5ed;
      font-size: calc(#{$font_size} + 2px);
      color: #4b4c4d;
      font-weight: bold;
      line-height: 48px;
    }
    .dialoginfo-info-info {
      height: calc(100% - 48px);
      overflow: auto;
      padding: 20px;
      .user {
        line-height: 24px;
        font-size: $font_size;
        color: #4b4c4d;
        font-weight: 400;
      }
      .user:hover {
        cursor: pointer;
      }
    }
    .dialoginfo-info-info::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
    .dialoginfo-info-info::-webkit-scrollbar-track {
      background: rgb(239, 239, 239);
      border-radius: 2px;
    }
    .dialoginfo-info-info::-webkit-scrollbar-thumb {
      background: #bfbfbf;
      border-radius: 10px;
    }
    .dialoginfo-info-info::-webkit-scrollbar-thumb:hover {
      background: #333;
    }
    .dialoginfo-info-info::-webkit-scrollbar-corner {
      background: $bg_color;
    }
    .dialoginfo-info-center {
      width: 40px;
    }
  }
  .dialoginfo-title-bg {
    justify-content: center !important;
  }
  .dialoginfo-title {
    display: flex;
    align-items: center;
    justify-content: center;
    > div {
      height: 48px;
      width: 190px;
      border: 1px solid $bg_color;
      font-weight: 400;
      font-size: calc(#{$font_size} + 2px);
      @include discen;
    }
    > div:first-child {
      border-radius: 4px 0 0 4px;
    }
    > div:last-child {
      border-radius: 0 4px 4px 0;
    }
    .active {
      background: $bg_color;
      color: #ffffff;
    }
    .none {
      color: $bg_color;
      background: #ffffff;
    }
  }
}
.organization {
  .dialoginfo {
    width: 640px;
    > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      > span {
        display: flex;
        align-items: center;
      }
      .el-input,
      .el-select {
        width: 200px;
      }
    }
    .textarea_input {
      padding-top: 10px;
      align-items: flex-start;
      height: 118px;
    }
    .textarea {
      width: 550px;
    }
    .upload_bg {
      padding-top: 10px;
      align-items: flex-start;
      justify-content: flex-start;
      height: 210px;
    }
    .upload {
      width: 200px;
      height: 200px;
      position: relative;
      .upload_add {
        width: 200px;
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        background: #c1c1c1;
      }
      .input {
        margin: 0;
        position: absolute;
        top: 0;
        left: 0;
      }
      input {
        opacity: 0;
      }
    }
  }
}
</style>
